package com.glodon.paas.web.resource;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import com.glodon.paas.consts.CommonsConfig;
import com.glodon.paas.util.DateUtil;
 
public class CommonsResource{
	/**
	 * 自检接口，可以根据level做不同级别的检查，
	 * 建议level = 0,1,2...
	 * 0：基本检查，仅接口调用
	 * 其他自定义
	 * @param level
	 * @return Map<String,String>
	 */
    @GET
    @Path("/health")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String,String> health(
    		@Context HttpServletRequest request,
    		@QueryParam("level")@DefaultValue("0") int level
    	) { 
    	Map<String,String> info = new HashMap<String,String>();
    	
    	info.put("level", String.valueOf(level));
    	info.put("statusCode", "200");
    	info.put("version", "1.0.0");    	
    	info.put("env", CommonsConfig.ENV);
    	info.put("appName", CommonsConfig.APP_NAME);
    	info.put("currentTime", DateUtil.formatDate(new Date(), DateUtil.DAFAULT_DATETIME_FORMAT));  //变化值，以此判断返回值非缓存
    	info.put("commitTime", "20130107");
    	try {
			info.put("ip", InetAddress.getLocalHost().getHostAddress());
		} catch (UnknownHostException e) {
			info.put("ip", "");
		}
    	int healthScore = 100;
    	String healthMessage = "good";
    	
    	/* 这里可以添加自己需要的检查项，如数据库调用等
    	 * 并根据检查结果，评估healthScore和healthMessage
    	 * ...
    	 */
    	if(level == 1){
    		// do Other
    	}
    	
		info.put("healthScore", String.valueOf(healthScore));
		info.put("healthMessage", healthMessage);
    	// 其他可选项
    	// info.put("comments", "cpu:50%,jvm…");
    	return info;
    }

    private static Properties properties = null;
    @GET
    @Path("/version")
    @Produces(MediaType.APPLICATION_JSON)
    public Properties version( ) throws IOException {
    	if(properties == null){
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("version.properties");
            properties = new Properties();
            properties.load(is);    		
    	}
        return properties;
    }
}
